package com.xfpp.javaDemo.proxy;

import java.io.File;
import java.io.FileWriter;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.net.URLClassLoader;

import javax.tools.JavaCompiler;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

public class CompileTest {
	public static void main(String[] args) throws Exception{
		String ln = "\r\t";
		String src = 
		"package com.xfpp.javaDemo.proxy;" + ln +

		"public class TankTimeProxy implements Moveable {" + ln +
		"	private Moveable t;" + ln +
			
		"	public TankTimeProxy(Moveable t) {"+ ln +
		"		super();" + ln +
		"		this.t = t;" + ln +
		"	}" + ln +
		
		"	@Override" + ln +
		"	public void move() {" + ln +
		"		long start = System.currentTimeMillis();" + ln +
		"		System.out.println(\"start time : \" + start);" + ln +
		"		t.move();" + ln +
		"		long end = System.currentTimeMillis();" + ln +
		"		System.out.println(\"调用此方法消耗的时间是：\" + (end - start) );" + ln +
		"	}" + ln +

		"}";
		
		String fileName = "E:/src/com/xfpp/javaDemo/proxy/TankTimeProxy.java";
		File f = new File(fileName);
		FileWriter fw = new FileWriter(f);
		fw.write(src);
		fw.flush();
		fw.close();
		
		JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
//		System.out.println(compile.getClass().getName());
		StandardJavaFileManager sjfm = compiler.getStandardFileManager(null, null, null);
		Iterable units = sjfm.getJavaFileObjects(fileName);
		CompilationTask ct = compiler.getTask(null, sjfm, null, null, null, units);
		ct.call();
		sjfm.close();
		
		URL[] urls = new URL[]{new URL("file:/E:/src/")};
		URLClassLoader ul = new URLClassLoader(urls);
		Class c = ul.loadClass("com.xfpp.javaDemo.proxy.TankTimeProxy");
		
		Constructor ctr = c.getConstructor(Moveable.class);
		Moveable m = (Moveable)ctr.newInstance(new Tank());
		m.move();
	}
}
